import { useRef, useState, useEffect, RefObject, useContext } from 'react'
import { Modal, Form, Space, Button, FormInstance, Select, Input, message } from 'antd';
import { OtherPersonSchema } from '@src/components/schema/caseSchema'
import Dictionary, { DictionaryItem } from '@js/dictionary';
import { checkIdCard } from '@src/assets/js/identityTest';
import { CaseContext } from '@src/pages/admin/pages/caseDetail/context';
import { awaitWrap, confirmAction } from '@js/tool'
import { addRequest, updateRequest, delRequest } from './ajax'

const { Item } = Form
const { Option } = Select
const { TextArea } = Input

const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 }
}

async function submitHandle (d: { [k: string]: any }, caseid: string, refreshFn: () => void) {
  let fn: (v: any) => Promise<any> = addRequest
  if (d.id) {
    fn = updateRequest
  }
  d.license_type = '身份证'
  d.caseid = caseid
  const hide = message.loading('提交中', 120)
  const [e] = await awaitWrap(fn(d))
  hide()
  if (e === null) {
    refreshFn()
  }
}

async function delHandle (d: OtherPersonSchema, refreshFn: () => void) {
  const hide = message.loading('删除中', 120)
  const [e] = await awaitWrap(delRequest(d.id))
  hide()
  if (e === null) {
    refreshFn()
  }
}

function getInitialValues (value: OtherPersonSchema | null, licenseTypeList: DictionaryItem[]) {
  if (value) {
    return value
  }
  return {
    name: undefined, // 全称姓名
    license_type: licenseTypeList[0].title, // 证照类型
    license: '', // 证照号
    structure: '', // 所在单位
    address: '', // 详细地址
    mobile: '', // 手机号
    email: '', // 邮箱
    tel: '', // 其他联系方式
    accountid:  '',
    action_subject:  '',
    address_type:  '',
    caseid:  '',
    certifyid:  '',
    create_datetime:  '',
  }
}

// 验证身份证
function validateLicense (formRef: RefObject<FormInstance>, value: string) {
  if (typeof value === 'string' && value.length) {
    const e = checkIdCard.test(value)
    if (e) {
      return Promise.reject(new Error(e))
    }
  }
  return Promise.resolve()
}

interface Props {
  value: OtherPersonSchema | null
  visible: boolean
  editable: boolean
  hide: () => void
}

function Main ({ value, visible, editable, hide }: Props) {
  const [licenseTypeList, setLicenseTypeList] = useState<DictionaryItem[]>([])
  const formRef = useRef<FormInstance>(null)
  const c = useContext(CaseContext)
  useEffect(() => {
    const d = new Dictionary()
    d.init('自然人证件类型')
      .then(() => {
        setLicenseTypeList(d.getList('自然人证件类型'))
      }).catch(e => console.error(e))
  }, [])
  useEffect(() => {
    if (visible) {
      const current = formRef.current
      const d = getInitialValues(value, licenseTypeList)
      if (current) {
        current.setFieldsValue(d)
      }
    } else {
      const current = formRef.current
      if (current) {
        current.resetFields()
      }
    }
  }, [value, visible, formRef])
  return (
    <Modal
      title={value ? ( editable ? '修改其他' : '其他详情' ) : '添加其他'}
      onCancel={() => hide()}
      visible={visible}
      footer={(
        <Space>
          {value && editable && <Button danger onClick={() => confirmAction(`您确定要删除${value.name}吗？`, () => { delHandle(value, () => { hide(); c.initOtherPerson() }) })}>删除</Button>}
          <Button onClick={() => hide()}>取消</Button>
          {editable && <Button type='primary' onClick={() => { formRef.current?.submit() }}>确定</Button>}
        </Space>
      )}
    >
      <Form ref={formRef} {...layout} onFinish={(d) => submitHandle(d, c.caseid, () => { c.initOtherPerson(); hide() })}>
        <Item name='id' noStyle><span /></Item>
        <Item name='name' label='姓名' rules={[{required: true, message: '姓名不能为空'}]}>
          <Input placeholder='请输入姓名' />
        </Item>
        <Item label='仲裁地位' name='action_subject'>
          <Input placeholder='请输入仲裁地位' />
        </Item>
        <Item label='身份证号码' name='license' rules={[{required: true, message: '身份证不能为空'}, { validator: (rule: any, value: string) => validateLicense(formRef, value) }]}>
          <Input placeholder='请输入证件号码' />
        </Item>
        <Item label='所在单位' name='structure'>
          <Input placeholder='请输入所在单位' />
        </Item>
        <Item label='地址' name='address' rules={[{ required: true, message: '地址不能为空' }]}>
          <TextArea placeholder='请输入地址' style={{ resize: 'none' }} />
        </Item>
        <Item label='手机号码' name='mobile' rules={[{ pattern: /^1\d{10}$/, message: '手机号码格式不正确' }, { required: true, message: '手机号码不能为空' }]}>
          <Input placeholder='请输入手机号码' maxLength={11} />
        </Item>
        <Item label='邮箱' name='email' rules={[{ type: 'email', message: '邮箱格式不正确' }]}>
          <Input placeholder='请输入邮箱' />
        </Item>
        <Item label='其他联系方式' name='tel'>
          <Input placeholder='请输入其他联系方式' />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
